# With this we, again, have two commands (hello, goodbye)
# and a built-in help message.
# Notice that the help message DOES NOT change when run as an option on the hello command.
# In addition we do not need to explicitly specify the commands.py -h | --help in the Options section to get a help command. 
# """Greeter.

# Usage:
#     docopt_lib.py hello <name> [--caps] [--greeting=<str>]
#     docopt_lib.py goodbye <name> [--caps] [--greeting=<str>]
#     docopt_lib.py (-h | --help)

# Options:
#     -h --help            Show this screen.
#     --caps               Uppercase the output.
#     --greeting=<str>     Greeting to use [default: Hello].

# Commands:
#    hello       Say hello
#    goodbye     Say goodbye

# """

"""Greeter.

Usage:
  docopt_lib.py hello <name> [--caps] [--greeting=<str>]
  docopt_lib.py goodbye <name> [--caps] [--greeting=<str>]
  docopt_lib.py (-h | --help)

Options:
  -h --help         Show this screen.
  --caps            Uppercase the output.
  --greeting=<str>  Greeting to use [default: Hello].

Commands:
   hello       Say hello
   goodbye     Say goodbye

"""

from docopt import docopt
from schema import Optional, Schema, SchemaError  # for error handling

HELLO = """usage: docopt_lib.py hello [options] [<name>]

  -h --help         Show this screen.
  --caps            Uppercase the output.
  --greeting=<str>  Greeting to use [default: Hello].
"""

GOODBYE = """usage: docopt_lib.py goodbye [options] [<name>]

  -h --help         Show this screen.
  --caps            Uppercase the output.
  --greeting=<str>  Greeting to use [default: Goodbye].
"""


# def hello(name):
#     print(f'hello, {name}')


# def goodbye(name):
#     print(f'goodbye, {name}')


def greet(args):
    output = f'{args["--greeting"]}, {args["<name>"]}!'
    if args['--caps']:
        output = output.upper()
    print(output)


schema = Schema({
    Optional('hello'): bool,
    Optional('goodbye'): bool,
    '<name>': str,
    Optional('--caps'): bool,
    Optional('--help'): bool,
    Optional('--greeting'): str
})

def validate(args):
    try:
        args = schema.validate(args)
        return args
    except SchemaError as e:
        exit(e)


if __name__ == "__main__":
    arguments = docopt(__doc__, options_first=True, version='1.0.0') # parse arguments from document string

    # if an argument called hello was passed, execute the hello logic.
    # if arguments.get('hello'):
    #     hello(arguments['<name>'])
    # elif arguments.get('goodbye'):
    #     goodbye(arguments['<name>'])

    # greet(arguments)

    # arguments['<command>'] == 'hello' for a old version
    if arguments.get('hello'):
        greet(validate(docopt(HELLO)))
    elif arguments.get('goodbye'):
        greet(validate(docopt(GOODBYE)))
    else:
        exit("{0} is not a command. \
          See 'options.py --help'.".format(arguments['<command>']))
